<?php
/**
 * Created by PhpStorm.
 * User: dev
 * Date: 2018/8/7
 * Time: 10:46
 */

namespace App\Services\ApiServer\Response\Node;

/**
 * eth节点
 * 
 */
class EthNode extends BaseNode
{
    /*
    * 订单
    */
    private $nodeOrder;

    /*
     * rpc节点
     */
    private $nodeRpc;

    /**
     * 构造函数
     * CamNode constructor.
     */
    function __construct(){
        parent::__construct();
        $ethNodeOrder = config('app.node.'.$this->blockDomain.'.eth_bibowallet_order_api');
        $ethNodeRpc = config('app.node.'.$this->blockDomain.'.eth_bibowallet_rpc_api');
        //判断用户连接的节点(根据客户端传值进行判断)
        $header = Request::header();
        $this->nodeOrder = $ethNodeOrder[0];
        $this->nodeRpc = $ethNodeRpc[0];
    }

    /**
     * eth 钱包地址余额
     * @DateTime 2018-08-13
     * @version  [version]
     * @param    {string}
     * @param    [type]     $category_name [description]
     * @param    [type]     $address       [description]
     * @param    [type]     $asset_id      [description]
     * @return   [type]                    [description]
     */
    public function getWalletBalance($address, $asset_id = null){
        $return = 0;
        if ($asset_id == '0x0000000000000000000000000000000000000000') {
            $return = $this->getEthBalance($address);
        }else{
            $return = $this->getTokenBalance($asset_id,$address);
        }
        return $return;
    }

    /**
     * 查询eth余额
     * @DateTime 2018-05-22
     * @version  [version]
     * @param    {string}
     * @return   [type]     [description]
     */
    public function getEthBalance($address){
        $url = $this->nodeRpc.'/eth/getBalance/'.$address;
        $result = sendCurl($url, '', 'POST');
        if(isset($result['code']) && $result['code'] == -1){
            $this->error($result['msg']);
        }
        return sprintf("%.0f",$result['data']['balanceInt']);
    }

    /**
     * 查询erc20资产余额
     * @DateTime 2018-05-22
     * @version  [version]
     * @param   {string}
     * @return  [type]     [description]
     */
    public function getTokenBalance($asset_id,$address){
        $url = $this->nodeRpc.'/eth/getTokenBalance/'.$asset_id.'/'.$address;
        $result = sendCurl($url, '', 'POST');
        if(isset($result['code']) && $result['code'] == -1){
            $this->error($result['msg']);
        }
        return $result['data']['tokenBalance'];
    }
}